/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function buildMenuWindow() {


    var _pageSize = 20;

    var fieldName = ['id', 'no', 'name', 'url', 'type', 'typeName', 'iconCls', 'note', 'status', 'menuCode', 'superCode'];
    var fieldLabel = ['ID', '序号', '名称', 'URL', '类型代码', '类型', '图标', '备注', '状态', '菜单编码', '上级菜单'];


    var saveServlet = '../../servlet/system/MenuSave';
    var loadServlet = '../../servlet/system/MenuLoad';
    var deleteServlet = '../../servlet/system/MenuDel';



    var currentMenuCode = '01';
    var currentMenuName = '主菜单'

    var theme = '菜单';
    var _pageSize = 20;
    var _title = currentOrgName + theme + '管理';


    var types = [[1, '菜单'], [2, '按钮']];
    var typesStore = new Ext.data.SimpleStore({
        fields: ['code', 'name'],
        data: types
    });

    var typesCombo = {
        xtype: 'combo',
        id: 'TypeCombo',
        store: typesStore,
        displayField: 'name',
        valueField: 'code',
        hiddenName: 'code',
        editable: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        fieldLabel: '类别',
        value: 1,
        selectOnFocus: true
    };
    //typesCombo.selectByValue(1);

    var inputForm = new Ext.FormPanel(
            {
                xtype: 'form',
                id: 'input-form',
                bodyStyle: 'padding:15px;background:transparent',
                frame: true,
                border: false,
                url: saveServlet,
                items: [{
                        name: fieldName[0],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[0],
                        hidden: true
                    }
                    , {
                        name: fieldName[1],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[1]
                    }
                    , {
                        name: fieldName[2],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[2],
                        allowBlank: false
                    }, {
                        name: fieldName[3],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[3],
                        allowBlank: false
                    }, typesCombo, {
                        name: fieldName[6],
                        id: fieldName[6],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[6],
                        allowBlank: true
                    }, {
                        name: fieldName[7],
                        id: fieldName[7],
                        xtype: 'textfield',
                        fieldLabel: fieldLabel[7],
                        allowBlank: true
                    }
                ],
                buttons: [{
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: function () {
                            var submitConfig = {
                                success: function (form, action) {
                                    store.reload();
                                    //parent.Ext.getCmp('OrganTree').getRootNode().reload();
                                    Ext.getCmp('MenuTree').getNodeById(currentMenuCode).reload();
                                    win.hide();
                                },
                                failure: function (form, action) {
                                    switch (action.failureType) {
                                        case Ext.form.Action.CONNECT_FAILURE:
                                            Ext.Msg.alert('提示', '网络连接失败');
                                            break;
                                        case Ext.form.Action.SERVER_INVALID:
                                            Ext.Msg.alert('提示', action.result.msg);
                                    }
                                },
                                params: {}
                            };
                            var token1 = new Date().getTime();
                            submitConfig.params.token = token;
                            submitConfig.params.token1 = token1;
                            if (type === 1)
                                submitConfig.params.cmd = 'create';
                            else {
                                submitConfig.params.id = checkboxSel.getSelected().get("id");
                                submitConfig.params.cmd = 'update';
                            }
                            submitConfig.params.currentMenuCode = currentMenuCode;
                            Ext.getCmp('input-form').getForm().submit(submitConfig);
                        }
                    }, {
                        text: '取消',
                        handler: function () {
                            win.hide();
                        }
                    }]
            }
    );
    var win = new Ext.Window({
        layout: 'form',
        width: 340,
        autoHeight: true,
        closeAction: 'hide',
        items: [inputForm]
    });
    var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改

    function addNew() {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                modal: true,
                items: [inputForm]
            });
        }
        type = 1;
        win.setTitle('增加' + theme);
        //if (updated)
        // Ext.getCmp('input-form').getForm().getEl().dom.reset();
        Ext.getCmp('input-form').getForm().reset();
        inputForm.form.reset();
        //alert("ok");
        //typesCombo.setRawValue(1);
        //
        //Ext.getCmp('TypeCombo').setRawValue(1);
        Ext.getCmp('TypeCombo').setValue(types[0][0]);
        //
        //Ext.getCmp(fieldName[]).setValue(currentOrgName);
        win.show();

        //alert('a');
        //loginForm.form.reset();

        //Ext.getCmp('code').enable();    
    }

    function update() {
        updated = true;
        if (checkboxSel.getSelections().length === 0) {
            Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
        } else if (checkboxSel.getSelections().length > 1) {
            Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
        } else {
            if (win === null) {
                win = new Ext.Window({
                    layout: 'form',
                    width: 340,
                    autoHeight: true,
                    closeAction: 'hide',
                    modal: true,
                    items: [inputForm]
                });
            }

            //alert(checkboxSel.getSelected().get('code'));
            type = 2;
            Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
            //Ext.Msg.alert("a",Ext.getCmp("code"));
            //Ext.getCmp('code').readOnly=true;
            //Ext.getCmp('YesNo').setValue(checkboxSel.getSelected().get("ismine"));

            //alert(str);
            //alert(Ext.getCmp('checkdate'));


            win.setTitle('修改' + theme);
            win.show();
            //Ext.getCmp('grid').getEl.mask();
            //applicationUI.mask();
            //Ext.getDom('win-title').innerHTML='修改监控设备信息';
        }
    }

    function remove() {
        if (checkboxSel.getSelections().length === 0) {
            Ext.Msg.alert("修改" + theme, "您还没有选择，需要先选择才能删除");
        } else {
            Ext.MessageBox.confirm('提示', '将删除该菜单项，和全部下级菜单项，及其它相关项<br/>确实要删除所选的记录吗?', function (btn) {
                if (btn === 'yes') {
                    var record = checkboxSel.getSelected();
                    var menuCode = record.get("menuCode");
                    var token1 = new Date().getTime();
                    var conn = new Ext.data.Connection();
                    conn.request({
                        url: deleteServlet, //提交的删除地址
                        params: {token: token, token1: token1, menuCode: menuCode},
                        method: 'post',
                        scope: this,
                        callback: function (options, success, response) {
                            if (success) {
                                var messager = Ext.decode(response.responseText);
                                if (messager.success) {
                                    Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                    store.reload(); //重新load数据   	
                                    Ext.getCmp('MenuTree').getNodeById(currentOrgCode).reload();
                                } else {
                                    Ext.Msg.alert('提示', messager.msg);
                                }

                            } else {
                                Ext.MessageBox.alert("提示", "所选记录删除失败！");
                            }
                        }
                    });
                }
            });
        }
    }

    var vroot = new Ext.tree.AsyncTreeNode({
        text: '主菜单',
        draggable: false,
        id: '01',
        expanded: true,
        leaf: false
    });

    var vloader = new Ext.tree.TreeLoader({url: "../../servlet/system/MenuTreeServlet", baseParams: {}});
    vloader.on('beforeload', function (loader, node) {
        loader.baseParams.id = node.id;
        loader.baseParams.isManager = true;
    });

    var treeMenu = new Ext.tree.TreePanel({
        title: '菜单结构', //机构树
        id: 'MenuTree',
        useArrows: true,
        lines: true,
        autoScroll: true,
        animate: true,
        enableDD: false,
        containerScroll: true,
        width: 300,
        rootVisible: true,
        collapsed: false,
        collapsible: false,
        split: true,
        region: 'west',
        //columnWidth: .4,
        root: vroot,
        loader: vloader
    });
    //treeMenu.expandAll();
    treeMenu.on('click', function (node) {
        currentMenuCode = node.id;
        currentMenuName = node.text;
        //alert(currentMenuName);
        grid.setTitle(currentMenuName + " " + theme + '管理');
        //alert(node.childNodes)
        store.load({params: {id: currentMenuCode, start: 0, limit: _pageSize}});
    });

    var checkboxSel = new Ext.grid.CheckboxSelectionModel({singleSelect: true});
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
        , baseParams: {start: 0, limit: _pageSize}
        , autoLoad: true
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        id: 'grid',
        store: store,
        region: 'center',
        sm: checkboxSel,
        columns: [
            checkboxSel,
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: fieldLabel[1], width: 50, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 120, sortable: true, dataIndex: fieldName[2]},
            {header: fieldLabel[3], width: 250, sortable: true, dataIndex: fieldName[3]},
            {header: fieldLabel[5], width: 120, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[7], width: 120, sortable: true, dataIndex: fieldName[7]},
            {header: fieldLabel[9], width: 120, sortable: true, dataIndex: fieldName[9], hidden: true}
        ],
        //autoExpandColumn: fieldName[2],
        //renderTo: Ext.getBody(),
        //width: 780,
        //height: 590,
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addNew},
            '-',
            {text: '修改', iconCls: 'icon-edit', handler: update},
            '-',
            {text: '删除', iconCls: 'icon-delete', handler: remove}
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        })
    });

    store.on('beforeload', function () {
        Ext.apply(this.baseParams, {id: currentMenuCode});
    });
    //store.load({params: {id: currentMenuCode, start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "border",
        //defaults: {
        //    collapsible: true,
        //    split: true,
        //    bodyStyle: 'padding:15px'
        //},
        items: [
            grid,
            treeMenu//grid
        ]
    });
}
Ext.onReady(buildMenuWindow);